using AdminApiTemplate.Api.Enums;
using AdminApiTemplate.Api.Helpers;
using AdminApiTemplate.Cache;
using AdminApiTemplate.Common.Exceptions;
using AdminApiTemplate.Common.Helpers;
using AdminApiTemplate.Common.Models;
using Microsoft.AspNetCore.Mvc;

namespace AdminApiTemplate.Api.Controllers.BaseControllers
{
    /// <summary>
    /// 不需要登录也可访问的
    /// </summary>
    public class FreeAccessController : Controller
    {
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="request"></param>
        /// <param name="tables"></param>
        /// <param name="fields"></param>
        /// <param name="orderByFieldsAll"></param>
        /// <returns></returns>
        public IActionResult GetPagedList<Tin, Tout>(Tin request, string tables, string fields, string orderByFieldsAll, params SqlParameterItem[] sps) where Tin : PagedRequest
        {
            return GetPagedList<Tin, Tout>(request, tables, fields, orderByFieldsAll, null, sps);
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <typeparam name="Tin"></typeparam>
        /// <typeparam name="Tout"></typeparam>
        /// <param name="request"></param>
        /// <param name="tables"></param>
        /// <param name="fields"></param>
        /// <param name="orderByFieldsAll"></param>
        /// <returns></returns>
        public IActionResult GetPagedList<Tin, Tout>(Tin request, string tables, string fields, string orderByFieldsAll, Action<List<Tout>> action, params SqlParameterItem[] sps) where Tin : PagedRequest
        {
            if (!request.Export.GetValueOrDefault())
            {
                return new WebHelper(HttpContext, request).Execute(SysUserTypeEnum.None, null, () =>
                {
                    var pagedList = DataHelper.GetPagedList<Tin, Tout>(request, tables, fields, orderByFieldsAll, sps);
                    if (action!=null && pagedList.Items!=null && pagedList.Items.Any())
                    {
                        action(pagedList.Items);
                    }
                    return pagedList;
                });
            }
            else
            {
                if (string.IsNullOrEmpty(request.ExportModule))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.CodeError, "导出失败，导出模块必填", "ExportModule必填");
                }

                if (string.IsNullOrEmpty(request.ExportFileName))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.CodeError, "导出失败，导出文件名必填", "ExportFileName必填");
                }

                if (!request.HasExportPermission.GetValueOrDefault())
                {
                    throw new WithCodeException((int)ErrorCodeEnum.NotAllowed, "导出失败，没有权限进行此操作。");
                }

                var host = ConfigHelper.GetSysConfig<string>("ApiHost", null);
                if (string.IsNullOrEmpty(host))
                {
                    throw new WithCodeException((int)ErrorCodeEnum.CodeError, "导出失败，请联系管理员配置ApiHost参数");
                }

                var module = request.ExportModule;
                var folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Exports", module);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var fileName = $"{request.ExportFileName}{RandomHelper.RequestId()}.xlsx";
                var fullName = Path.Combine(folder, fileName);

                Task.Run(() =>
                {
                    var data = DataHelper.GetPagedList<Tin, Tout>(request, tables, fields, orderByFieldsAll, sps);
                    ExcelHelper.Export(fullName, data.Items);
                });

                return new WebHelper(HttpContext, request).Execute(SysUserTypeEnum.None, null, () =>
                {
                    return $"{host}/api/Common/Export?module={module}&fileName={fileName}";
                });
            }
        }
    }
}
